/**
 * 与三数之和思路一样
 * 前两个数看成一个整体
 * 
 */
var fourSum = function (nums, target) {
    const res = [];
    let len = nums.length; //注意不是length-1!!
    nums.sort((a, b) => a - b);
    for (let k = 0; k < len-3; k++) {//注意循环的边界
        if (k && (nums[k - 1] == nums[k])) continue;
        for (let i = k+1; i < len-2; i++) { //注意循环的边界
            if (i>k+1 && (nums[i - 1] == nums[i])) continue;
            let left = i + 1;
            let right = len - 1;
            while (left < right) {
                let sum = nums[k] + nums[i] + nums[left] + nums[right];
                if (sum <target) left++;
                else if (sum >target) right--;
                else {
                    res.push([nums[k],nums[i], nums[left], nums[right]]);
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    };
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    left++;
                    right--
                }
            }
        }
    }

    return res;
};